package com.metamech.vorpal;

import java.io.IOException;
import java.io.Writer;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;

import com.metamech.jabber.Session;
import com.metamech.jabber.xml.Packet;
import com.metamech.vorpal.handler.MessageHandler;


public class User {
	String username;
	String password;
	String hash;
	String sequence;
	String token;
	Roster roster;
	  
	// Resource (String) to Session object
	Hashtable resources = new Hashtable();	
	LinkedList messageStore = new LinkedList();
	
	// Primary session
	Session activeSession;
	
	public User(String username) { 
		roster = new Roster(username); 
	}
	
	

	public void setPassword(String password){ 
		this.password = password; 
	}
	
	public String getPassword(){ 
		return password;
	}
	
	public void setHash(String value) { 
		hash = value; 
	}
	
	public String getHash() { 
		return hash;  
	}

	public void setSequence(String value) { 
		sequence = value;
	}
	
	public String getSequence(){ 
		return sequence; 
	}

	public void setToken(String value){ 
		token = value;
	}
	
	public String getToken(){
		return token;
	}
	
	public Roster getRoster() { 
		return roster;	
	}
	
	// Stored messages for later delivery (store & forward)	
	public void storeMessage(Packet msg){ 
		messageStore.add(msg); 
	}
	
    // Deliver stored messages
	public void deliverMessages(){
		while (messageStore.size() > 0){
			Packet storedMsg = (Packet)messageStore.removeFirst();
			storedMsg.setSession(activeSession);
			storedMsg.setTo(storedMsg.getTo());
			MessageHandler.deliverPacket(storedMsg);
		}
	}

	public Iterator getSessions(){
		return resources.values().iterator();
	}

	public void changePriority(Session session){
		if (activeSession.getPriority() < session.getPriority()){
			activeSession = session;
		}
	}

	public void addSession(Session session){
		resources.put(session.getJID().getResource(),session);
		if (activeSession == null){
			activeSession = session;
		} else if (activeSession.getPriority() < session.getPriority()){
			activeSession = session;
		}
		deliverMessages();
	}

	public void removeSession(Session session){
		resources.remove(session.getJID().getResource());
		activeSession = null;

		Iterator sessionIterator = resources.values().iterator();
		if (sessionIterator.hasNext()){
			activeSession = (Session)sessionIterator.next();
			while (sessionIterator.hasNext()){
				Session sess = (Session)sessionIterator.next();
				if (sess.getPriority() > activeSession.getPriority()){
					activeSession = sess;
				}
			}
		}
	}

	public Writer getWriter(String resource) throws IOException {
		Session session;
		if (resource == null){
			session = activeSession;
		} else if (resource.length() == 0){
			session = activeSession;
		} else {
			session = (Session)resources.get(resource);
		}
		if (session == null){
			return null;
		}
		return session.getWriter();
	}
}